<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item label="用户名称" prop="real_name">
        <el-input
          v-model="queryParams.real_name"
          placeholder="请输入用户名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="登录账号" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入登录账号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="角色" prop="role_ids">
        <el-select v-model="queryParams.role_ids" multiple placeholder="请选择角色">
          <el-option
            v-for="item in roleOptions"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数据权限" prop="is_admin">
        <el-select v-model="queryParams.is_admin" placeholder="数据权限" clearable style="width: 240px">
          <el-option label="管理者" value="1" />
          <el-option label="普通员工" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="登录状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="登录状态" clearable style="width: 240px">
          <el-option label="启用" value="1" />
          <el-option label="停用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col> -->
    </el-row>

    <el-table v-loading="loading" :data="userList">
      <el-table-column label="用户名称" prop="real_name" :show-overflow-tooltip="true" />
      <el-table-column label="登录账户" align="center" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="角色" align="center" prop="role_title" width="160" :show-overflow-tooltip="true" />
      <el-table-column label="数据权限" align="center" prop="is_admin">
        <template slot-scope="scope">
					<el-tag v-if="scope.row.is_admin == '1'">管理者</el-tag>
					<el-tag type="success" v-else>普通员工</el-tag>
				</template>
      </el-table-column>
      <el-table-column label="企微账号" align="center" prop="wechat_user_id" width="160" :show-overflow-tooltip="true" />
      <el-table-column label="企微主体" align="center" prop="business_entity" width="100" />
      <el-table-column label="状态" align="center" key="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="1"
            inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.userId !== 1">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-key" @click="handleResetPwd(scope.row)">重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="用户名称" prop="real_name">
          <el-input v-model="form.real_name" placeholder="请输入用户名称" maxlength="30" />
        </el-form-item>
        <el-form-item label="登录账号" prop="name">
          <el-input v-model="form.name" placeholder="请输入登录账号" maxlength="30" />
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!form.id">
          <el-input v-model="form.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password/>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="roleIds" multiple placeholder="请选择角色">
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.title"
              :value="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据权限">
          <el-radio-group v-model="form.is_admin">
            <el-radio label="1">管理者</el-radio>
            <el-radio label="0">普通员工</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="绑定企微账号">
          <el-input v-model="form.wechat_user_id"  placeholder="请输入"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser, resetUserPwd, changeUserStatus, addRole, updateRole } from "@/api/system/user";
import { listRole } from "@/api/system/role";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  components: { Treeselect },
  data() {
    return {
      loading: true, // 遮罩层
      ids: [],// 选中数组
      single: true,// 非单个禁用
      multiple: true, // 非多个禁用
      total: 0,// 总条数
      userList: null,// 用户表格数据
      title: "",// 弹出层标题
      open: false,// 是否显示弹出层
      roleOptions: [],// 角色选项
      form: {},
      roleIds:[],
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "登录账号不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '登录账号长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        real_name: [
          { required: true, message: "用户名称不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' },
          { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.loading = false;
    this.getList();
    this.getRoleList()
  },
  methods: {
    /** 查询角色列表 */
    getRoleList(){
      listRole().then(res => {
        this.roleOptions = res.data
      })
    },
    /** 查询用户列表 */
    getList(){
      this.loading = true;
      listUser(this.queryParams).then(res => {
        const data = res.data.data
        data.forEach(item => {
          let arr = item.role
          let str = arr.map(s => s.title)
          item.role_title = str.toString()
        });
        this.userList = data
        this.total = res.data.total;
        this.loading = false;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "停用" : "启用";
      this.$modal.confirm('确认要"' + text + '""' + row.name + '"用户吗？').then(function() {
        let ststus = row.status == 0 ? '1' : '0'
        return changeUserStatus(row.id, ststus);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.roleIds = []
    },
    // 表单重置
    reset() {
      this.form = {};
      this.roleIds = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryParams");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.form = {
        is_admin : "1"
      }
      this.open = true
      this.title = "添加用户"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = JSON.parse(JSON.stringify(row))
      this.form.is_admin = row.is_admin.toString()

      this.roleIds = this.form.role.map(item => item.name)
      console.log(this.roleIds)
      this.title = "修改用户";
      this.open = true;
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.name + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
        inputValidator: (value) => {
          if (/<|>|"|'|\||\\/.test(value)) {
            return "不能包含非法字符：< > \" ' \\\ |"
          }
        },
      }).then(({ value }) => {
          resetUserPwd(row.name, value).then(response => {
            this.$modal.msgSuccess("修改成功，新密码是：" + value);
          });
        }).catch(() => {});
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            delete this.form.role
            delete this.form.role_title
            updateUser(this.form).then(res => {
              const params = {
                user_id: this.form.id,
                role_names: this.roleIds
              }
              updateRole(params).then(res1 => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
            });
          } else {
            addUser(this.form).then(res => {
              const params = {
                user_id: res.data,
                role_names: this.roleIds
              }
              addRole(params).then(res1 => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function() {
        return delUser(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
  }
};
</script>

<style>
input[aria-hidden=true]{
    display: none !important;
}

</style>